$(function () {
    tabledata();
    layuiEdit();
    createTime_search();
    uploadpic();
});
// 加载列表
function tabledata() {
    layui.use('table', function () {
        var form = layui.form;
        var table = layui.table;
        table.render({
            elem: "#blogDataTable",
            //data: data,
            page: true,
            even: true,
            limits: [10, 20, 30],
            limit: 10,
            url: '/post/showList',
            toolbar: '#blogDataTable',
            id: 'dataTable',
            cols: [[
                {type: 'checkbox', fixed: 'left'},
                {field: 'postId', title: 'bolg编号'},
                {
                    field: 'allowComment', title: '是否允许评论', templet: function (d) {
                        if (d.allowComment === 0) {
                            return "允许"
                        } else {
                            return "<font color='red'>不允许</font>"
                        }
                    }
                },
                // {
                //     field: 'newsImg', title: '新闻配图', templet: function (d) {
                //         return "<img  src='" + d.newsImg + "'>";
                //     }
                // },
                {field: 'postContent', title: '发帖内容'},
                {field: 'postContentMd', title: '发帖内容markdown'},
                {
                    field: 'postDate', title: '发帖日期', templet: function (d) {
                        return fmt(d.postDate);
                    }
                },
                // {field: 'postStatus', title: '发帖状态'},
                // {field: 'postSummary', title: '发帖摘要'},
                // {field: 'postThumbnail', title: '缩略图'},
                // {field: 'postTitle', title: '发帖标题'},
                // {field: 'postType', title: '发帖类型'},
                {
                    field: 'postUpdate', title: '更新日期', templet: function (d) {
                        return fmt(d.postUpdate);
                    }
                },
                // {field: 'postUrl', title: '发帖链接'},
                // {field: 'userId', title: '用户编号'},
                {field: 'logicDel', title: '操作', toolbar: '#blogBar'}
            ]],
            request: {
                page: 'page' //页码的参数名称，默认：page
                , pageSize: 'limit' //每页数据量的参数名，默认：limit
            }
        });
        var $ = layui.$,
            active = {
                reload: function () {
                    var createTime = $("#blog_createTime").val(),
                        title = $("#blog_Auctitle").val();

                    table.reload("dataTable", {
                        url: '/post/showList',
                        where: {
                            createTime: createTime,
                            title: title
                        },
                        page: {
                            page: 1
                        }
                    });
                }
            };
        $("#blog_search").on("click", function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : "";
        })
    });

}

function fmt(timestamp) {

    // var year = now.getFullYear();
    // var month = now.getMonth() + 1;
    // var date = now.getDate();
    // var hour = now.getHours();
    // var minute = now.getMinutes();
    // var second = now.getSeconds();
    // return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;

    //13位时间戳转换
    var date = new Date(timestamp / 1);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d + " " + h + ":" + minute + ":" + second;
//10位时间戳转换
//             function timestampToTime2(timestamp) {
//     var date = new Date(timestamp * 1000);
//     var y = date.getFullYear();
//     var m = date.getMonth() + 1;
//     m = m < 10 ? ('' + m) : m;
//     var d = date.getDate();
//     d = d < 10 ? ('0' + d) : d;
//     var h = date.getHours();
//     h = h < 10 ? ('0' + h) : h;
//     var minute = date.getMinutes();
//     var second = date.getSeconds();
//     minute = minute < 10 ? ('0' + minute) : minute;
//     second = second < 10 ? ('0' + second) : second;
//     return y + '-' + m + '-' + d + " " + h + ":" + minute + ":" + second;
//             }
}

//条件搜索框之时间
function createTime_search() {
    layui.use('laydate', function () {
        var laydate = layui.laydate;
        laydate.render({
            elem: '#blog_createTime'
            , type: 'datetime'
            , range: true
        });
    });
}

//编辑
function layuiEdit() {
    layui.use('table', function () {
        var thas = this;
        var form = layui.form;
        var table = layui.table;
        //监听表格复选框选择
        table.on('checkbox(dataTable)', function (obj) {
        });
        //监听工具条
        table.on('tool(dataTable)', function (obj) {
            var _self = this;
            var data = obj.data;
            //console.log(data);
            //表格查看
            if (obj.event === 'detail') {
                layer.open({
                    type: 1,
                    title: "查看博客信息",
                    maxmin: true,
                    offset: '100px',
                    area: ['400px', '850px'],
                    content: $("#win_show_news"),// iframe的url
                    success: function (layero, index) {
                        //机械性赋值
                        $("#show_news_title").text(data.title);
                        $("#show_news_img").attr("src", data.newsImg);
                        $(document).ready(function () {
                            $("#show_news_content").html(data.content);
                        });
                    }
                });

            }
            //表格删除
            else if (obj.event === 'del_blog') {
                var token = localStorage.getItem("token");
                layer.confirm('真的删除这条数据么？', function (index) {
                    $.ajax({
                        type: "delete",
                        headers: {'Authorization': token},
                        url: "/post/del/" + data.postId ,
                        data: null,
                        dataType: "json",
                        async: false,
                        success: function (data) {
                            //console.log(data);
                            if (data.data == 1) {
                                window.location.href = "/post/";
                                layer.msg(data.msg, {time: 1 * 1000});
                            } else {
                                layer.msg(data.msg, {time: 1 * 1000});
                            }
                        }
                    });
                    layer.close(index);
                });
            }

            //表格修改
            else if (obj.event === 'edit') {
                var acu = JSON.stringify(data);
                var indexs = layer.open({
                    type: 1,
                    title: "修改博客信息",
                    maxmin: true,
                    offset: '100px',
                    area: ['100%', '100%'],
                    content: $("#win-blog-update"),// iframe的url
                    success: function (layero, index) {
                        console.log(data);
                        var wueditor;
                        layui.use('layer', function () {
                            var form = layui.form;
                            wueditor = editormd("content-editormd", {//注意1：这里的就是上面的DIV的id属性值
                                placeholder: '欢迎使用',
                                width: "90%",
                                height: 640,
                                emoji: true,//emoji表情，默认关闭
                                syncScrolling: "single",
                                path: "/static/common/editor/lib/",//注意2：你的路径
                                saveHTMLToTextarea: true,//注意3：这个配置，方便post提交表单
                                // 图片上传
                                imageUpload: true,
                                imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
                                imageUploadURL: "/upload/uploadFile"
                            });


                        });
                        var allow = document.getElementsByName("allow_comment");//拍卖阶段
                        for (var i = 0; i < allow.length; i++) {
                            if (data.allowComment == allow[i].value) {
                                $(allow[i]).next().click();
                            }
                        }
                        $("#blog_title_update").val(data.postTitle);
                        $("#blogId").val(data.postId);
                        $('#demo1').attr('src', data.postThumbnail); //图片链接（base64）
                        $("#content-editormd-markdown-doc").val(data.postContentMd);
                        layui.use('form', function () {
                            $("#blog_category").val(parseInt(data.postType));
                            form.render();
                            //editormd.markdownToHTML(data.postContentMd);
                        });
                        $('#blog_update').on('click', function () {
                            var markdownContent = wueditor.getMarkdown(),
                                htmlContent = wueditor.getHTML(),
                                title = $("#blog_title_update").val(),
                                allowed = $("input[name='allow_comment']:checked").val(),
                                mtype = $("#blog_category").val(),
                                blogId = $("#blogId").val();
                            if (title == null || title === "") {
                                layer.msg("请填写公告缩略内容！");
                                return;
                            }
                            if (markdownContent == null || markdownContent === "") {
                                layer.msg("请填写文本框内容！");
                                return;
                            }
                            var user = localStorage.getItem("user");
                            var token = localStorage.getItem("token");
                            datas = {};
                            datas.postContentMd = markdownContent;
                            datas.postContent = htmlContent;
                            datas.allowComment = allowed;
                            datas.postTitle = title;
                            datas.postType = mtype;
                            datas.postId = blogId;
                            map = {};
                            map.PostVo = datas;
                            map.user = user;
                            //提交数据
                            $.ajax({
                                type: "PUT",
                                url: "/post/update",
                                headers: {'Authorization': token},
                                data: JSON.stringify(map),
                                contentType: "application/json; charset=utf-8",
                                dataType: 'json',//预期服务器返回的数据类型
                                beforeSend: function () {
                                    //让提交按钮失效
                                    //$('#news_update').prop('disabled', "true");
                                },
                                success: function (data) {
                                    console.log(data);
                                    layui.use('layer', function () {
                                        var layer = layui.layer;
                                        layer.open({
                                            content: "操作成功！",//提示信息
                                            success: function () {
                                                layer.msg(data.msg, {time: 1 * 1000}, function () {
                                                    window.location.href = "/post/";
                                                });
                                            }
                                        });

                                        //$("#news_res_update").click();
                                    });

                                },
                                complete: function () {
                                    //$('#sbbtn').prop('disabled', false);
                                }
                            });
                        });
                    }
                });
                layer.full(indexs);
            }
        });
    });
}

//上传图片
function uploadpic() {
    layui.use('upload', function () {
        var $ = layui.jquery
            , upload = layui.upload;

        //普通图片上传
        var uploadInst = upload.render({
            elem: '#imgupload',
            url: 'http://crawler_upload.6ack.com/upload/layedit',
            before: function (obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    $('#demo1').attr('src', result); //图片链接（base64）
                });
            },
            done: function (res) {
                //如果上传失败
                if (res.code > 0) {
                    return layer.msg('上传失败');
                }
                //上传成功
                $("#demoText").html(res.data.src);
                console.log(res);
            },
            error: function () {
                //演示失败状态，并实现重传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function () {
                    uploadInst.upload();
                });
            }
        });
    });
}